<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 登录页面 - 支持账号密码、短信、钉钉、微信、飞书登录
 * 尊重劳动成果是一种美德
 */

// 设置session目录权限
ini_set('session.save_path', sys_get_temp_dir());
session_start();

// 检查是否已经登录
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    header('Location: index.php');
    exit;
}

// 从配置文件获取管理员账号信息和插件配置
$config = include 'config.php';
$adminUser = $config['admin_user'] ?? ['username' => 'admin', 'password' => 'admin123'];
$dingtalkEnabled = $config['plugins']['dingtalk']['enabled'] ?? false;
$smsEnabled = $config['plugins']['sms']['enabled'] ?? false;
$wechatEnabled = $config['plugins']['wechat']['enabled'] ?? false;
$feishuEnabled = $config['plugins']['feishu']['enabled'] ?? false;

// 检查是否有任何第三方登录启用
$hasThirdPartyLogin = $smsEnabled || $dingtalkEnabled || $wechatEnabled || $feishuEnabled;

// 处理登录请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    // 验证用户名和密码
    if ($username === $adminUser['username'] && $password === $adminUser['password']) {
        $_SESSION['logged_in'] = true;
        $_SESSION['username'] = $username;
        header('Location: index.php');
        exit;
    } else {
        $error = '用户名或密码错误';
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>氚云API管理系统 - 登录</title>
    <link rel="stylesheet" href="css/variables.css">
    <link rel="stylesheet" href="css/main.css">
</head>
<body>
    <div class="login-container">
        <div class="login-box">
            <h1 class="login-title">氚云API管理系统</h1>
            
            <?php if (isset($error)): ?>
            <div class="error-message" style="background-color: #ffebee; color: #c62828; padding: 10px; border-radius: 4px; margin-bottom: 20px; text-align: center;">
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label for="username" class="form-label">用户名</label>
                    <input type="text" id="username" name="username" class="form-input" required placeholder="请输入用户名">
                </div>
                
                <div class="form-group">
                    <label for="password" class="form-label">密码</label>
                    <input type="password" id="password" name="password" class="form-input" required placeholder="请输入密码">
                </div>
                
                <div class="form-group">
                    <button type="submit" class="btn btn-login">登录</button>
                </div>
                
                <?php if ($hasThirdPartyLogin): ?>
                <div class="form-group">
                    <div class="divider">
                        <span>或</span>
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="login-button-group">
                        <?php if ($smsEnabled): ?>
                        <button type="button" class="btn btn-login-sms" onclick="loginWithSms()">短信</button>
                        <?php endif; ?>
                        <?php if ($dingtalkEnabled): ?>
                        <button type="button" class="btn btn-login-dingtalk" onclick="loginWithDingtalk()">钉钉</button>
                        <?php endif; ?>
                        <?php if ($wechatEnabled): ?>
                        <button type="button" class="btn btn-login-wechat" onclick="loginWithWechat()">微信</button>
                        <?php endif; ?>
                        <?php if ($feishuEnabled): ?>
                        <button type="button" class="btn btn-login-feishu" onclick="loginWithFeishu()">飞书</button>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </form>
            
        </div>
    </div>
    
    <!-- 短信登录弹窗 -->
    <div id="smsLoginModal" class="login-modal">
        <div class="login-modal-content">
            <div class="login-modal-header">
                <h3>短信验证登录</h3>
                <span class="login-modal-close" onclick="closeSmsModal()">&times;</span>
            </div>
            <div class="login-modal-body">
                <div id="sms-step-1" class="sms-step">
                    <div class="form-group">
                        <label for="sms-phone" class="form-label">手机号</label>
                        <input type="tel" id="sms-phone" class="form-input" placeholder="请输入11位手机号" maxlength="11">
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-login" id="send-code-btn" onclick="sendSmsCode()">获取验证码</button>
                    </div>
                </div>
                
                <div id="sms-step-2" class="sms-step" style="display:none;">
                    <div class="form-group">
                        <label for="sms-code" class="form-label">验证码</label>
                        <input type="text" id="sms-code" class="form-input" placeholder="请输入6位验证码" maxlength="6">
                        <small class="form-help" id="sms-phone-display"></small>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-login" onclick="verifySmsLogin()">验证并登录</button>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-secondary" id="resend-code-btn" onclick="sendSmsCode()" disabled>
                            <span id="countdown">60</span>s 后重新发送
                        </button>
                    </div>
                </div>
                
                <div id="sms-error" class="error-message" style="display:none; margin-top: 15px;"></div>
            </div>
        </div>
    </div>
    
    <!-- 钉钉登录弹窗 -->
    <div id="dingtalkLoginModal" class="login-modal">
        <div class="login-modal-content">
            <div class="login-modal-header">
                <h3>钉钉扫码登录</h3>
                <span class="login-modal-close" onclick="closeDingtalkModal()">&times;</span>
            </div>
            <div class="login-modal-body" style="text-align: center; padding: 40px 24px;">
                <div id="dingtalk-qrcode">
                    <p style="color: #666; margin-bottom: 20px;">正在生成二维码...</p>
                </div>
                <div id="dingtalk-error" class="error-message" style="display:none; margin-top: 15px;"></div>
            </div>
        </div>
    </div>
    
    <!-- 微信登录弹窗 -->
    <div id="wechatLoginModal" class="login-modal">
        <div class="login-modal-content">
            <div class="login-modal-header">
                <h3>微信扫码登录</h3>
                <span class="login-modal-close" onclick="closeWechatModal()">&times;</span>
            </div>
            <div class="login-modal-body" style="text-align: center; padding: 40px 24px;">
                <div id="wechat-qrcode">
                    <p style="color: #666; margin-bottom: 20px;">正在生成二维码...</p>
                </div>
                <div id="wechat-error" class="error-message" style="display:none; margin-top: 15px;"></div>
            </div>
        </div>
    </div>
    
    <!-- 飞书登录弹窗 -->
    <div id="feishuLoginModal" class="login-modal">
        <div class="login-modal-content">
            <div class="login-modal-header">
                <h3>飞书扫码登录</h3>
                <span class="login-modal-close" onclick="closeFeishuModal()">&times;</span>
            </div>
            <div class="login-modal-body" style="text-align: center; padding: 40px 24px;">
                <div id="feishu-qrcode">
                    <p style="color: #666; margin-bottom: 20px;">正在生成二维码...</p>
                </div>
                <div id="feishu-error" class="error-message" style="display:none; margin-top: 15px;"></div>
            </div>
        </div>
    </div>
    
    <script>
    // 短信登录
let smsCountdown = 60;
let smsTimer = null;
let currentPhone = '';

function loginWithSms() {
    document.getElementById('smsLoginModal').classList.add('show');
    document.getElementById('sms-step-1').style.display = 'block';
    document.getElementById('sms-step-2').style.display = 'none';
    document.getElementById('sms-error').style.display = 'none';
    document.getElementById('sms-phone').value = '';
    document.getElementById('sms-code').value = '';
}

function closeSmsModal() {
    document.getElementById('smsLoginModal').classList.remove('show');
    if (smsTimer) {
        clearInterval(smsTimer);
        smsTimer = null;
    }
}

function sendSmsCode() {
    const phone = document.getElementById('sms-phone').value;
    const errorDiv = document.getElementById('sms-error');
    
    if (!phone) {
        showSmsError('请输入手机号');
        return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        showSmsError('手机号格式不正确');
        return;
    }
    
    currentPhone = phone;
    const sendBtn = document.getElementById('send-code-btn');
    sendBtn.disabled = true;
    sendBtn.textContent = '发送中...';
    
    fetch('plugin/sms/send-code.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: phone })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('sms-step-1').style.display = 'none';
            document.getElementById('sms-step-2').style.display = 'block';
            document.getElementById('sms-phone-display').textContent = '验证码已发送至 ' + phone;
            errorDiv.style.display = 'none';
            startCountdown();
        } else {
            showSmsError(data.message || '发送失败');
            sendBtn.disabled = false;
            sendBtn.textContent = '获取验证码';
        }
    })
    .catch(error => {
        showSmsError('请求失败：' + error.message);
        sendBtn.disabled = false;
        sendBtn.textContent = '获取验证码';
    });
}

function startCountdown() {
    smsCountdown = 60;
    const resendBtn = document.getElementById('resend-code-btn');
    const countdownSpan = document.getElementById('countdown');
    resendBtn.disabled = true;
    
    smsTimer = setInterval(() => {
        smsCountdown--;
        countdownSpan.textContent = smsCountdown;
        
        if (smsCountdown <= 0) {
            clearInterval(smsTimer);
            resendBtn.disabled = false;
            resendBtn.innerHTML = '重新发送';
        }
    }, 1000);
}

function verifySmsLogin() {
    const code = document.getElementById('sms-code').value;
    
    if (!code) {
        showSmsError('请输入验证码');
        return;
    }
    
    if (!/^\d{6}$/.test(code)) {
        showSmsError('验证码必须为6位数字');
        return;
    }
    
    fetch('plugin/sms/verify-login.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: currentPhone, code: code })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            window.location.href = result.redirect || 'index.php';
        } else {
            showSmsError(result.message || '验证失败');
        }
    })
    .catch(error => {
        showSmsError('请求失败：' + error.message);
    });
}

function showSmsError(message) {
    const errorDiv = document.getElementById('sms-error');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
}

    // 钉钉扫码登录
    function loginWithDingtalk() {
        document.getElementById('dingtalkLoginModal').classList.add('show');
        document.getElementById('dingtalk-qrcode').innerHTML = '<p style="color: #666; margin-bottom: 20px;">正在生成二维码...</p>';
        document.getElementById('dingtalk-error').style.display = 'none';
        
        fetch('plugin/dingtalk/get-qrcode.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 显示二维码提示并跳转
                document.getElementById('dingtalk-qrcode').innerHTML = '<p style="color: #333; margin-bottom: 20px;">正在跳转到钉钉授权页面...</p>';
                setTimeout(() => {
                    window.location.href = data.qrcode_url;
                }, 500);
            } else {
                showDingtalkError('获取登录信息失败：' + data.message);
            }
        })
        .catch(error => {
            showDingtalkError('请求失败：' + error.message);
        });
    }
    
    function closeDingtalkModal() {
        document.getElementById('dingtalkLoginModal').classList.remove('show');
    }
    
    function showDingtalkError(message) {
        const errorDiv = document.getElementById('dingtalk-error');
        document.getElementById('dingtalk-qrcode').innerHTML = '';
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }
    
    // 微信登录
    function loginWithWechat() {
        document.getElementById('wechatLoginModal').classList.add('show');
        document.getElementById('wechat-qrcode').innerHTML = '<p style="color: #666; margin-bottom: 20px;">正在生成授权信息...</p>';
        document.getElementById('wechat-error').style.display = 'none';
        
        fetch('plugin/wechat/get-auth-url.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 显示跳转提示
                document.getElementById('wechat-qrcode').innerHTML = '<p style="color: #333; margin-bottom: 20px;">正在跳转到微信授权页面...</p>';
                setTimeout(() => {
                    window.location.href = data.auth_url;
                }, 500);
            } else {
                showWechatError('获取登录信息失败：' + data.message);
            }
        })
        .catch(error => {
            showWechatError('请求失败：' + error.message);
        });
    }
    
    function closeWechatModal() {
        document.getElementById('wechatLoginModal').classList.remove('show');
    }
    
    function showWechatError(message) {
        const errorDiv = document.getElementById('wechat-error');
        document.getElementById('wechat-qrcode').innerHTML = '';
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }
    
    // 飞书登录
    function loginWithFeishu() {
        document.getElementById('feishuLoginModal').classList.add('show');
        document.getElementById('feishu-qrcode').innerHTML = '<p style="color: #666; margin-bottom: 20px;">正在生成授权信息...</p>';
        document.getElementById('feishu-error').style.display = 'none';
        
        fetch('plugin/feishu/get-auth-url.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 显示跳转提示
                document.getElementById('feishu-qrcode').innerHTML = '<p style="color: #333; margin-bottom: 20px;">正在跳转到飞书授权页面...</p>';
                setTimeout(() => {
                    window.location.href = data.auth_url;
                }, 500);
            } else {
                showFeishuError('获取登录信息失败：' + data.message);
            }
        })
        .catch(error => {
            showFeishuError('请求失败：' + error.message);
        });
    }
    
    function closeFeishuModal() {
        document.getElementById('feishuLoginModal').classList.remove('show');
    }
    
    function showFeishuError(message) {
        const errorDiv = document.getElementById('feishu-error');
        document.getElementById('feishu-qrcode').innerHTML = '';
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }
    </script>
    <script src="js/auth.js"></script>
</body>
</html>